package com.dyna.core.utils;

import com.dyna.core.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;

/**
 * 模拟数据
 */
@Slf4j
public class MockUtil {

    private final static String fileContent;

    static {
        String filePath = "D:\\workspace\\java\\dyna-cloud\\dyna-cloud-pro\\mock\\ChineseText.txt";
        // 1. 读取文件内容
        try {
            fileContent = new String(Files.readAllBytes(Paths.get(filePath)),  "UTF-8");
        } catch (IOException e) {
            log.error("初始化MockUtil读取文件失败", e);
            throw new CustomException("初始化MockUtil读取文件失败");
        }
    }

    /**
     * 单词
     */
    public static String word() {
        return word(1, 2);
    }

    public static String word(int minLength, int maxLength) {
        String result = getRandomSubstring(fileContent, minLength, maxLength);
        return result;
    }

    /**
     * 从给定字符串中随机获取n到m个连续字符
     * @param word 源字符串
     * @param minLength 最小长度 (包含)
     * @param maxLength 最大长度 (包含)
     * @return 随机子串
     */
    public static String getRandomSubstring(String word, int minLength, int maxLength) {
        // 参数校验
        if (word == null || word.isEmpty())  {
            throw new IllegalArgumentException("输入字符串不能为空");
        }

        if (minLength <= 0 || maxLength <= 0) {
            throw new IllegalArgumentException("长度参数必须大于0");
        }

        if (minLength > maxLength) {
            throw new IllegalArgumentException("最小长度不能大于最大长度");
        }

        if (minLength > word.length())  {
            throw new IllegalArgumentException("最小长度不能超过字符串长度");
        }

        Random random = new Random();

        // 计算实际可能的最大长度
        int actualMaxLength = Math.min(maxLength,  word.length());

        // 随机生成长度 (n ≤ length ≤ m)
        int length = random.nextInt(actualMaxLength  - minLength + 1) + minLength;

        // 计算可能的起始位置范围 (0 ≤ start ≤ word.length()  - length)
        int maxStart = word.length()  - length;
        int start = random.nextInt(maxStart  + 1);

        // 返回子串
        return word.substring(start,  start + length);
    }

}
